import Snake from "./Snake";
import Food from "./Food";
import ScorePanel from "./ScorePanel";
import * as events from "events";

class GameControl {
    // 蛇
    snake: Snake
    // 食物
    food: Food
    // 记分牌
    scorePanel: ScorePanel

    // 存储蛇的移动方向
    direction: string = ''
    // 记录游戏是否结束
    isLive = true

    constructor() {
        this.snake = new Snake()
        this.food = new Food()
        this.scorePanel = new ScorePanel(10, 2)
        this.init()
    }

    init() {
        // 绑定键盘按键
        document.addEventListener('keydown', this.keydownHandler.bind(this))
        // 调用
        this.run()
    }

    /*
    * ArrowLeft ArrowRight ArrowUp ArrowDown       谷歌
    * Left Right Up Down             IE
    * */

    // 创建键盘按下的响应函数
    keydownHandler(event: KeyboardEvent) {
        if (event.key) {
            this.direction = event.key
        }
    }

    // 蛇移动
    run() {
        // 获取蛇当前坐标
        let X = this.snake.X
        let Y = this.snake.Y
        // 根据按键方向修改相应值
        switch (this.direction) {
            case 'ArrowUp':
            case 'Up':
                Y -= 10
                break
            case 'ArrowDown':
            case 'Down':
                Y += 10
                break
            case 'ArrowLeft':
            case 'Left':
                X -= 10
                break
            case 'ArrowRight':
            case 'Right':
                X += 10
                break
        }

        // 检查是否吃到食物
        this.checkEat(X, Y)
        // 设置蛇位置
        try {
            this.snake.X = X
            this.snake.Y = Y
        } catch (e) {
            alert((e as Error).message + 'GAME OVER!')
            this.isLive = false
        }
        this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
    }

    // 检查蛇是否吃到食物
    checkEat(X: number, Y: number) {
        if (X === this.food.x && Y === this.food.y) {
            // 食物位置重置
            this.food.change()
            // 增加分数
            this.scorePanel.addScore()
            // 蛇长度增加
            this.snake.addBody()
        }
    }
}


export default GameControl